MediaViewer.tsx ➔ MediaViewer   B
last analyzed

Complexity

Conditions 5

Size

Total Lines 52
Code Lines 44

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 44
dl 0
loc 52
rs 8.3573
c 0
b 0
f 0
cc 5

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
import React, {useEffect, useState} from "react";
2
import {useParams} from "react-router-dom";
3
import {getReadableDate} from "../utils";
4
import {MediaResource} from "../interfaces";
5
6
const apiGetEndpoint = "/api/get";
7
8
function MediaViewer(): JSX.Element {
9
  const {id} = useParams<{id: string}>();
10
  const [resource, setResource] = useState<MediaResource | null>(null);
11
  const [isLoading, setIsLoading] = useState(true);
12
13
  useEffect(() => {
14
    async function fetchMediaResource() {
15
      setIsLoading(true);
16
      const request = await fetch(apiGetEndpoint, {
17
        method: "POST",
18
        body: JSON.stringify({"resourceId": id})
19
      });
20
21
      const response = await request.json();
22
      const document = response.result;
23
24
      if (document) {
25
        setResource(document);
26
      }
27
      setIsLoading(false);
28
    }
29
30
    fetchMediaResource();
31
  }, [id]);
32
33
  const calculateFileSize = (r: MediaResource): string  => {
34
    return (Math.round(r.size / (1024 * 1024) * 100)) / 100 + "MB";
35
  };
36
37
  return (
38
    <div style={{backgroundColor: "rgb(33, 37, 41)", padding: "15px", marginTop: "2rem"}}>
39
      {resource?.type.includes("image") &&
40
        <img className="media" src={resource.privateUrl} alt="requested image"/>}
41
      {resource?.type.includes("video") &&
42
        <video className="media" src={resource.privateUrl} autoPlay controls/>}
43
      {resource &&
44
        <div>
45
          <p className="inline">File name: {resource.name}</p>
46
          &nbsp;
47
          &nbsp;
48
          <p className="inline">File type: {resource.type}</p>
49
          <br />
50
          <p className="inline">File size: {calculateFileSize(resource)}</p>
51
          &nbsp;
52
          &nbsp;
53
          <p className="inline">Uploaded on: {getReadableDate(resource)}</p>
54
        </div>
55
      }
56
      {!resource && !isLoading && <h1>It looks like the resource you are looking for does not exist</h1>}
57
      {!resource && isLoading && <h1>Loading...</h1>}
58
    </div>
59
  );
60
}
61
62
export default MediaViewer;
63